import {
	Inject
} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api', 'DepartService', 'AuthService')
export class AuthModels {
	constructor($scope, $state, dialog, http, api, DepartService, service) {
		var appScope = $scope.$parent;

		function getTreeNode() {
			return appScope.getTreeNode();
		}

		appScope.changeState();
		var NODE;
		if (!(NODE = getTreeNode())) {
			appScope.select(appScope.welcome);
			return;
		}

		var ID = NODE.id;

		var q = $scope.q = {};

		var columns = [{
			name: '序号',
			width: 50,
			field: 'id',
			cellTemplate: '<div class="x-grid-inner">{{index+1}}</div>'
		}, {
			name: '移除',
			width: 100,
			field: 'id',
			cellTemplate: '<div class="x-grid-inner"><span class="btn-text" title="移除" ng-click="grid.appScope.remove(grid.appScope.editable ? index : grid.getCellValue(row, col))"><i class="fa fa-remove"></i></span></div>'
		}, {
			name: '类型',
			width: 100,
			field: 'objType',
			cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col, \'objType\')"></div>'
		}, {
			name: '对象名',
			width: 100,
			field: 'name'
		}];

		var tempAuths;
		var loadData = $scope.loadData = function(params) {
			var node = getTreeNode();
			if (!node) return;
			params = params || {};
			angular.extend(params, {
				categoryId: node.id
			});
			api.gridLoad({
				name: 'auth_models',
				params: params,
				scope: $scope,
				clearMultiSelections: true,
				success: function(r, options) {
					var _scope = this;
					var auths = r.columns;

					var authCols = getAuthColumns(auths);
					service.authorization(auths, r.data);
					_scope.gridOptions.columns = [].concat(columns, authCols);
					_scope.fields = angular.merge({}, _scope.fields, r.fields);
					_scope.gridOptions.rightId = node.id;
					tempAuths = service.getAuths(r.data, node.id);
				}
			});
		};

		var query = $scope.query = function(params) {
			var _params = angular.extend({}, q, params);
			loadData(_params);
		}

		$scope.importUsers = function() {
			var ids = ($scope.gridOptions.data || []).map(function(item) {
				return service.setId(item);
			});
			var type = 'U';
			DepartService.select(ID).then(function(users) {
				var options = $scope.gridOptions;
				var _data = (users || []).filter(function(user) {
					var id = service.setId(user.id, type);
					return ids.indexOf(id) == -1;
				}).map(function(user) {
					var id = service.setId(user.id, type);
					var _user = {
						id: id,
						type: type,
						name: user.username
					};
					_user[service.param.id] = user.id;
					_user[service.param.type] = type;
					_user[service.param.nodeid] = ID;
					return _user
				});
				var data = options.data || [];
				options.data = [].concat(data, _data);
			});
		}

		$scope.importDeparts = function() {
			var ids = ($scope.gridOptions.data || []).map(function(item) {
				return service.setId(item);
			});
			var type = 'B';
			api.select({
				title: '选择部门',
				postTree: 'basic/branch/treeBranch'
			}).then(function(nodes) {
				var options = $scope.gridOptions;
				var _data = (nodes || []).filter(function(node) {
					var id = service.setId(node.id, type);
					return ids.indexOf(id) == -1;
				}).map(function(node) {
					var id = service.setId(node.id, type);
					var _node = {
						id: id,
						type: type,
						name: node.text
					};
					_node[service.param.id] = node.id;
					_node[service.param.type] = type;
					_node[service.param.nodeid] = ID;
					return _node
				});
				var data = options.data || [];
				options.data = [].concat(data, _data);
			});
		}

		$scope.editable = false;

		function toggleText() {
			$scope.toggleText = $scope.editable ? '切换视图模式' : '进入编辑模式';
		}
		toggleText();
		$scope.toggle = function(force) {
			if ($scope.editable) {
				if (force !== true) {
					var newAuths = service.getAuths($scope.gridOptions.data);
					if (!service.equals(newAuths, tempAuths)) {
						dialog.confirm('当前有修改需要提交吗？').result.then(function(r) {
							if (r) {
								http.post({
									name: 'auth_save',
									params: {
										purviews: newAuths,
										categoryId: ID
									},
									success: function() {
										tempAuths = newAuths;

										$scope.toggle(true);
									}
								})
							} else {
								$scope.toggle(true);
							}
						});
						return;
					}
				}
				$scope.editable = false;
				query(false);
			} else {
				api.clearGridSelection($scope);
				$scope.editable = true;
			}
			toggleText();
		}

		$scope.remove = function(id) {
			if ($scope.editable) {
				$scope.gridOptions.data.splice(id, 1);
			} else {
				var once = id != null;
				var ids = once ? [id] : api.getGridSelectedIds($scope);
				dialog.confirm(once ? '确定要移除当前用户权限？' : '确定要移除这些用户权限？').result.then(function(r) {
					if (r) {
						http.post({
							name: 'auth_remove',
							params: {
								ids: ids
							},
							success: function() {
								query(false);
							}
						})
					}
				});
			}
		}

		$scope.removeAll = function() {
			dialog.confirm('确定要清空当前权限配置？').result.then(function(r) {
				if (r) {
					$scope.gridOptions.data = [];
				}
			});
		}

		$scope.save = function() {
			var newAuths = service.getAuths($scope.gridOptions.data);

			if (service.equals(newAuths, tempAuths)) {
				dialog.notify({
					type: 'danger',
					message: '没有需要保存的修改'
				});
			} else {
				http.post({
					name: 'auth_save',
					params: {
						purviews: newAuths,
						categoryId: ID
					},
					success: function() {
						tempAuths = newAuths;

						$scope.toggle(true);
					}
				})
			}
		}

		function getAuthColumns(cols) {
			return (cols || []).map(function(col) {
				return angular.extend(col, {
					width: 100,
					cellTemplate: '<div class="x-grid-inner" ng-if="grid.appScope.editable"><input type="checkbox" ng-model="row.entity.auth[col.colDef.index]" /></div><div class="x-grid-inner" ng-if="!grid.appScope.editable"><span class="text-danger" ng-if="!row.entity.auth[col.colDef.index]"><i class="fa fa-times-circle"></i></span><span class="text-success" ng-if="row.entity.auth[col.colDef.index]"><i class="fa fa-check-circle"></i></span></div>'
				})
			});
		}

		$scope.cellSelect = function(grid, row, col, event) {
			var el = event.target;
			if (!$scope.editable) return;
			var index = col.colDef.index;
			if (index == null) return;
			if (el.tagName.toUpperCase() != 'INPUT' || el.type != 'checkbox') {
				service.setAuth(grid, row, index);
			}
			var auth = grid.getRowValue(row, 'auth');
			if (auth[index] === false) {
				row.isSelected = false;
			}
		}

		$scope.gridOptions = {
			columns: [],
			enableRowSelection: false,
			forceFit: false,
			rowTemplate: '<td ng-repeat="(colIndex, col) in grid.renderedColumns track by col.uid" col="col" ng-style="setStyle(col)" ng-click="grid.appScope.cellSelect(grid, row, col, $event)" grid-view-cell></td>',
			onRegisterApi: function(api, grid) {
				var _scope = grid.appScope;
				_scope.api = api;
				if (api.selection) {
					api.selection.on.rowSelectionChanged(_scope, function(row, event) {
						if (_scope.editable) {
							row.grid.columns.forEach(function(c) {
								var index = c.colDef.index;
								if (index != null) {
									service.setAuth(grid, row, index, row.isSelected);
								}
							});
						}
					});
				}
			}
		};

		$scope.fileds = {
			'types': {
				'1': '用户',
				'2': '部门'
			}
		}

		$scope.mapping = function(grid, row, col, field) {
			return api.mapping({
				grid: grid,
				row: row,
				col: col,
				field: field,
				scope: $scope
			});
		}

		$scope.hasSelected = function() {
			return api.hasGridSelected($scope);
		}
		$scope.hasSelectedRecords = function() {
			return api.hasGridSelectedRecords($scope);
		}

		query();
	}
}